package cmd

import (
	"colly/models"
	"colly/services"
	"github.com/panjf2000/ants/v2"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"gorm.io/gorm"
	"sync"
	"time"
)

func init() {
	runDir, _ = getExecutableDir()
	offerCmd.PersistentFlags().IntVarP(&id, "id", "i", 0, "pk id")
	offerCmd.PersistentFlags().StringVarP(&proxyFile, "proxy", "p", runDir+"/clash.yaml", "clash file path")
	offerCmd.PersistentFlags().StringVarP(&currency, "currency", "C", "All", "server path name")
	rootCmd.AddCommand(offerCmd)
}

var offerCmd = &cobra.Command{
	Use:   "offer",
	Short: "This is the offer command",
	Long:  "This is the offer command",
	PreRun: func(cmd *cobra.Command, args []string) {
		if proxyFile == "" {
			proxyFile = "./clash.yaml"
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		golds := make([]models.Gold, 0)
		Db.Where("enable = ?", 1).Find(&golds)
		if len(golds) < 1 {
			Log.Info("No Record Found")
			time.Sleep(time.Second * 5)
			return
		}

		defer ants.Release()
		var wg sync.WaitGroup
		pool, _ := ants.NewPool(30)
		defer pool.Release()
		task := func(url, proxyFile, cy string, id int, wg *sync.WaitGroup, db *gorm.DB, log *logrus.Logger) func() {
			return func() {
				defer wg.Done()
				services.Offer(url, proxyFile, cy, id, db, log)
			}
		}
		for _, gold := range golds {
			//Log.Infof("task_id: %d, game: %s, server: %s", index+1, gold.Game, gold.Title)
			if currency == "All" {
				wg.Add(2)
				pool.Submit(task(gold.Uri(), proxyFile, "CNY", gold.ID, &wg, Db, Log))
				pool.Submit(task(gold.Uri(), proxyFile, "USD", gold.ID, &wg, Db, Log))
			} else {
				wg.Add(1)
				pool.Submit(task(gold.Uri(), proxyFile, currency, gold.ID, &wg, Db, Log))
			}

			//Log.Infof("url: %s %s %s\n", gold.Uri(), proxyFile, currency)
			//Db.Table(game.TableName()).Where("id = ?", game.ID).Update("enable", 1)
		}
		wg.Wait()
	},
}
